import React from 'react';
import classNames from 'classnames';
import filter from 'filter-anything';

class TextArea extends React.Component {
    displayName = 'TextArea';

    state = {
        _value: this.props.value || ''
    }

    onChange = (e) => {
        const v = e.target.value;
        this.setState({
            _value: v
        });
    }

    onKeyUp = (e) => {
        if (this.props.onKeyUp) { this.props.onKeyUp(e.target.value, e); }
        if (e.keyCode === 13) {
            this.onEnter(e);
        }
    }

    onEnter (e) {
        if (this.props.onEnter) {
            this.props.onEnter(this.input.value, e);
        }
    }

    onInput = (e) => {
        if (this.props.onInput) { this.props.onInput(e.target.value, e); }
        this.props.autoHeight && this.autoHeight(e);
    }

    autoHeight (event) {
        const ele = event.target;
        if (!this.initHeight) {
            this.initHeight = ele.clientHeight;
        }
        if (ele.scrollHeight > this.initHeight) {
            ele.style.height = 'auto';
            ele.style.overflowY = 'hidden';
            ele.scrollTop = 0; // 防抖动
            const pd = this.getPadding(ele);
            ele.style.height = `${ele.scrollHeight + pd}px`;
        }
    }

    getPadding (ele) {
        const pdTop = parseFloat(this.css(ele, 'paddingTop'));
        const pdBottom = parseFloat(this.css(ele, 'paddingBottom'));
        const bdTop = parseFloat(this.css(ele, 'borderTopWidth'));
        const bdBottom = parseFloat(this.css(ele, 'borderBottomWidth'));

        return pdTop + pdBottom + bdTop + bdBottom;
    }

    css (el, style, fake) {
        if (window.getComputedStyle) {
            return window.getComputedStyle(el, fake)[style];
        }
        if (el.currentStyle) {
            return el.currentStyle[style];
        }
        return null;
    }

    onBlur = (e) => {
        const v = e.target.value;
        if (this.props.onChange) { this.props.onChange(v, e); }
    }

    render () {
        let {className, style, disabled} = this.props;
        const others = filter(this.props, [], ['className', 'style', 'value', 'onChange', 'onInput', 'onKeyUp', 'ref', 'autoHeight']);

        className = classNames('cm-input-wrapper', className, {
            'cm-input-disabled': disabled
        });

        return <div className={className} style={style}>
            <textarea className='cm-input' {...others} value={this.state._value} 
                onChange={this.onChange} onInput={this.onInput} onKeyUp={this.onKeyUp} onBlur={this.onBlur}
            ></textarea>
        </div>;
    }
}

export default TextArea;
